package cn.kgc.vue.controller;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.kgc.vue.commons.QueryCondition;
import cn.kgc.vue.entity.Student;
import cn.kgc.vue.exceptions.BusinessException;
import cn.kgc.vue.response.ResponseResult;
import cn.kgc.vue.response.ResponseStatus;
import cn.kgc.vue.service.StudentService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.List;

/**
 * @author 课工场
 * @date 2024/10/6
 * @description
 */
@RestController
@RequestMapping("student")
public class StudentController {

    @Resource
    private StudentService studentService;

    // 学生数据的分页
    @PostMapping("page")
    public ResponseResult studentPage(@RequestBody QueryCondition<Student> queryCondition) {
        return studentService.studentPage(queryCondition);
    }


    // 学生信息编辑或添加
    @PostMapping("addOrUpdate")
    public ResponseResult addOrUpdateStudent(@RequestBody Student student) {

        try {
            studentService.saveOrUpdate(student);
            return ResponseResult.success();
        } catch (DuplicateKeyException e) {
            throw new BusinessException(ResponseStatus.ERROR.getCode(), student.getStudentNo() + "学号已存在");
        }

    }

    // 删除学生信息
    @DeleteMapping("delete/{id}")
    public ResponseResult deleteStudent(@PathVariable("id") Integer id) {
        studentService.removeById(id);
        return ResponseResult.success();
    }

    // 批量导入
    @PostMapping("import")
    public ResponseResult importStudent(MultipartFile file)  {

        if (file.isEmpty()){
            return  ResponseResult.fail().message("请选择上传文件");
        }


        // 创建导入参数对象   设置表格参数
        ImportParams importParams = new ImportParams();
        importParams.setTitleRows(1);
        importParams.setHeadRows(1);

        // 解析excel文件
        try {
            InputStream inputStream = file.getInputStream();
            List<Student> students = ExcelImportUtil.importExcel(inputStream, Student.class, importParams);
            return  studentService.importStudent(students);
        }catch (BusinessException e){
            throw  e;
        }catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

  // 批量导出
    @PostMapping("export")
    public void exportStudents(@RequestBody QueryCondition<Student> queryCondition, HttpServletResponse response){

        studentService.exportStudents(queryCondition,response);
    }

}
